package com.lsn.watermall.exception;

import com.lsn.watermall.entity.Result;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

@RestControllerAdvice
/**
 * 全局异常处理只会对@RequestMapping标注的方法起作用 POST，GET不行
 */
public class WaterExceptionHandler {
    @ExceptionHandler(WaterException.class)
    public Result handleException(Exception e){
        System.out.println("WaterException Handler:"+e.getMessage());
        WaterException waterException = ((WaterException) e);
        return Result.error("ERR9999",waterException.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(Exception e){
        System.out.println("handleMethodArgumentNotValidException:"+e.getMessage());
        MethodArgumentNotValidException e1 = ((MethodArgumentNotValidException) e);
        return Result.error("ERR9999",e1.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(SQLException.class)
    public Result handleSQLException(Exception e){
        System.out.println("SQLException 123:"+e.getMessage());
        return Result.error("ERR9999","数据库异常，请联系管理员");
    }
}
